import React, { useEffect } from "react"
import { Button, Typography } from "antd"
import { Link } from "react-router-dom"
import { ProductItemFace } from "../components/productItem"
import { CartItem } from "../pages/cart"
import stores from "../stores"
import $http from "../utils/require"

const { Title } = Typography

export const add2Cart = (item: ProductItemFace) => {

    let cart: CartItem[] = []
    if (localStorage.getItem('cart')) {
        cart = JSON.parse(localStorage.getItem('cart') as string)
    }

    let oldItem = cart.find(el => el._id === item._id)
    if (oldItem) {
        cart.forEach(el => {
            if (el._id === item._id) {
                el.count++
            }
        })
    } else {
        cart.push({
            ...item,
            count: 1
        })
    }


    localStorage.setItem('cart', JSON.stringify(cart))
}
export const delCartItem = (cartItems: CartItem[], index: number) => {
    let cart: CartItem[] = cartItems
    cart.splice(index, 1)
    localStorage.setItem('cart', JSON.stringify(cart))
    return [...cart]
}

export const getCart = () => {
    let cart: CartItem[] = []
    if (localStorage.getItem('cart')) {
        cart = JSON.parse(localStorage.getItem('cart') as string)
    }
    return cart
}

export const updateCartItem = (productId: string, count: number) => {
    let cart: CartItem[] = []
    if (localStorage.getItem('cart')) {
        cart = JSON.parse(localStorage.getItem('cart') as string)
    }

    cart.forEach(el => {
        if (el._id === productId) {
            el.count = count
        }
    })

    localStorage.setItem('cart', JSON.stringify(cart))

    return [...cart]
}

export const TotalPrice = ({ cart, setTotalPrice }: { cart: CartItem[], setTotalPrice: (price: number) => void }) => {
    const getTotalPrice = () => {
        return cart.reduce((currval, nextval) => {
            return currval += nextval.price * nextval.count
        }, 0).toFixed(2)
    }

    useEffect(() => {
        setTotalPrice(+getTotalPrice())
    }, [cart])

    return (
        <>
            <Title level={5}>商品总价：{getTotalPrice()}</Title>
        </>
    )
}

export const getItemCount = () => {
    let obj = JSON.parse(localStorage.getItem('cart') as string)
    if (obj) {
        return obj.length
    }
    return 0
}


export const Pay = ({
    totalAmount,
    subject,
    body,
    products,
    address,
    userId = stores.User.user._id
}: {
    totalAmount: number,
    subject: string,
    body: string,
    products: { product: string, count: number }[],
    address: string,
    userId?: string
}) => {

    const go2pay = () => {
        $http['alipay']({
            totalAmount,
            subject,
            body,
            products,
            address,
            userId
        }).then(res => {
            location.href = res.result
            console.log(res);
        })
    }

    return stores.User.token ?
        <Button onClick={() => go2pay()}>提交订单</Button> :
        <Button>
            <Link to="/signin">登录</Link>
        </Button>
}